import { defineStore } from "pinia";
import request from "../axios/index";
import router from "../router/index";
import { ElMessage } from "element-plus";

export const mainStore = defineStore("main", {
  state: () => ({
    adminName: "",
    token: "",
    cacheData: null,
  }),
  getters: {},
  actions: {
    //登录
    async login(userName: string, password: string) {
      try {
        const userInfo = { userName, password };
        const response = await request.post("/admin/system/login", userInfo);
        const { token } = response.data.data;
        sessionStorage.setItem("token", token);
        sessionStorage.setItem("userName", userName);
        this.adminName = userName;
        this.token = token;
        router.replace({
          path: "/smart-e/admin/index/notice",
        });
      } catch (e: any) {
        ElMessage.error("登录失败");
        throw new Error(e);
      }
    },
    //退出登录
    loginOut() {
      this.token = "";
      sessionStorage.clear();
      router.replace({
        path: "/login",
      });
    },
    //临时存取编辑数据
    addCacheData(data: any): void {
      this.cacheData = data;
    },
  },
});
